//
//  MYGUploadView.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/15.
//

import UIKit

class MYGUploadView: UIView {
    var tapCloseCompletion:(()->Void)?
   
    lazy var tableView: UITableView = {
        let control = UITableView.init(frame: .zero, style: .grouped)
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.estimatedRowHeight = 85
        control.backgroundColor = .clear
        control.ww_foldable = true
        control.register(UINib.init(nibName: "MYGCloudDiskUploadDownloadCell", bundle: nil), forCellReuseIdentifier: "MYGCloudDiskUploadDownloadCell")
        control.register(UINib.init(nibName: "SafeRootTabHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "SafeRootTabHeaderView")
        return control
    }()
  
    @objc func backAction() {
        if let cc = self.tapCloseCompletion  {
            cc()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
      
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
     
        NotificationCenter.default.addObserver(self, selector: #selector(addUploadTask), name: Notification.Name("MYGCloudDiskUploadManager_addUploadTask"), object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(uploadProgressChanged(_ :)), name: Notification.Name("MYGCloudDiskUploadManager_progress"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(uploadStatusChanged), name: Notification.Name("MYGCloudDiskUploadManager_uploadStatusChanged"), object: nil)

        tableView.reloadData()
        
    }
    
    
    @objc func addUploadTask() {
        self.tableView.reloadData {
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
//                let lastIndex = max(0, MYGUploadManager.shared.uploadingArray.count - 1)
//                if let cell = self.tableView.cellForRow(at: IndexPath(item: lastIndex, section: 0)) as? MYGCloudDiskUploadDownloadCell {
//                    cell.startDownload()
//                }
//            })
        }
    }
    
    @objc func uploadProgressChanged(_ noti:Notification) {
        guard let uploadModel = noti.object as? MYGUploadModel else {
            return
        }
        for (index, model) in MYGUploadManager.shared.uploadingArray.enumerated() {
            if uploadModel.name == model.name {
                MYGUploadManager.shared.uploadingArray[index] = uploadModel
                if let cell = tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? MYGCloudDiskUploadDownloadCell {
                    cell.bindUploadData(model)
                }
                break
            }
        }
    }
    
    @objc func uploadStatusChanged() {
        self.tableView.reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension MYGUploadView:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGCloudDiskUploadDownloadCell", for: indexPath) as! MYGCloudDiskUploadDownloadCell
        if indexPath.section == 0 {
            let model = MYGUploadManager.shared.uploadingArray[indexPath.row]
            cell.bindUploadData(model)
        }else {
            let model = MYGUploadManager.shared.uploadedArray[indexPath.row]
            cell.bindUploadData(model)
        }
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SafeRootTabHeaderView") as! SafeRootTabHeaderView
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(gestureTapped(_:)))
        header.addGestureRecognizer(tapGesture)
        
        if section == 0 {
            header.contentLB.text = "进行中"
        }else {
            header.contentLB.text = "已完成"
        }
        header.tag = section
        header.isExtend = self.tableView.ww_isSectionFolded(section)
        return header
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return MYGUploadManager.shared.uploadingArray.count
        }
        return MYGUploadManager.shared.uploadedArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    @objc func gestureTapped(_ ges:UIGestureRecognizer) {
        guard let header = ges.view else {return}
        let section = header.tag
        self.tableView.ww_foldSection(section, fold: !self.tableView.ww_isSectionFolded(section))
    }
}


